// DrawPoint.ts
import * as THREE from 'three'; // 如果后续需要与 Three.js 集成，可以保留此导入
import drawborad from './drawboard';
class DrawPoint {
  

  constructor(params) {
    this.canvas = params.canvas;
    this.data = params.data;
    this.threePoints = params.threePoints;
    this.parent = params.parent;
    this.dcanvas = params.dcanvas;
    this.mesh = params.mesh;
    ///this.connector = new Connector(MrgData.threeMrg.scene, this.threePoints, this.parent, this.dcanvas);
    this.init();
  }

  /**
   * 初始化方法，开始绘制所有点
   */
  private init(): void {
    console.log("Ports Data:", this.data.port);
    const ports = this.data.port;
    const slots = this.data.slot;

    const ctx = this.canvas.getContext('2d');
    if (!ctx) {
      console.error('无法获取 2D 上下文');
      return;
    }

    // 清空画布
    //ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 绘制端口（蓝色半透明）
    ports.forEach(port => {
      const { x, y } = port.pos;
      const { width, height } = port.size;
      this.drawPoint(ctx, x, y, width, height, 'rgba(0, 0, 255, 0.5)', 'black');
      //console.log("画布的大小:", this.canvas, this.canvas.width, this.canvas.height, port, x, y, width, height)
      // 自动连接到一个随机的 Three.js 点
     // this.connector.connectToThreePoint(port.pos, width, height, this.canvas.width, this.canvas.height);

    });
    setTimeout(()=>{
      new drawborad({
        ctx:ctx,
        mesh:this.mesh,
        data:this.data
      })
    }, 2000)
    
    

    // 绘制插槽（红色半透明）
    /*
    slots.forEach(slot => {
      const { x, y } = slot.pos;
      const { width, height } = slot.size;
      this.drawPoint(ctx, x, y, width, height, 'rgba(255, 0, 0, 0.5)', 'black');
      //this.connector.connectToThreePoint(slot.pos, width, height, this.canvas.width, this.canvas.height);
    });
    */

    // 移除旧的点击事件监听器，防止重复绑定
    //this.canvas.removeEventListener('click', this.handleClick);
    // 添加新的点击事件监听器
    //this.canvas.addEventListener('click', this.handleClick.bind(this));
  }

  /**
   * 绘制单个点（矩形）到 Canvas 上
   * @param ctx Canvas 渲染上下文
   * @param x 绘制起点的 X 坐标
   * @param y 绘制起点的 Y 坐标
   * @param width 矩形的宽度
   * @param height 矩形的高度
   * @param fillStyle 填充颜色
   * @param strokeStyle 边框颜色
   */
  private drawPoint(
    ctx: CanvasRenderingContext2D,
    x: number,
    y: number,
    width: number,
    height: number,
    fillStyle: string = 'rgba(0, 0, 255, 0.5)',
    strokeStyle: string = 'black'
  ): void {
    ctx.fillStyle = fillStyle;
    ctx.fillRect(x, y, width, height);

    ctx.strokeStyle = strokeStyle;
    ctx.lineWidth = 2;
    ctx.strokeRect(x, y, width, height);
  }

  /**
   * 动态更新点数据并重新绘制
   * @param newData 新的端口和插槽数据
   */
  public updateData(newData: DrawPointParams['data']): void {
    this.data = newData;
    this.init();
  }

  /**
   * 处理点击事件
   * @param event MouseEvent
   */
  private handleClick(event: MouseEvent): void {
    const rect = this.canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    // 检查点击是否在某个端口或插槽内
    const clickedPort = this.data.port.find(port => this.isInside(x, y, port));
    const clickedSlot = this.data.slot.find(slot => this.isInside(x, y, slot));

    if (clickedPort) {
      console.log('Clicked on port:', clickedPort);
      this.selectedPoint = { type: 'port', data: clickedPort };
      this.highlightPoint(
        clickedPort.pos.x,
        clickedPort.pos.y,
        clickedPort.size.width,
        clickedPort.size.height
      );
      this.triggerSelection();
    } else if (clickedSlot) {
      console.log('Clicked on slot:', clickedSlot);
      this.selectedPoint = { type: 'slot', data: clickedSlot };
      this.highlightPoint(
        clickedSlot.pos.x,
        clickedSlot.pos.y,
        clickedSlot.size.width,
        clickedSlot.size.height
      );
      this.triggerSelection();
    } else {
      console.log('Clicked on empty space');
      this.selectedPoint = null;
      this.init(); // 重绘，去除高亮
    }
  }

  /**
   * 检查点 (x, y) 是否在给定的端口或插槽内
   * @param x X 坐标
   * @param y Y 坐标
   * @param item 端口或插槽
   * @returns 是否在范围内
   */
  isInside(x, y, item) {
    return (
      x >= item.pos.x &&
      x <= item.pos.x + item.size.width &&
      y >= item.pos.y &&
      y <= item.pos.y + item.size.height
    );
  }

  /**
   * 高亮显示选中的点
   * @param x X 坐标
   * @param y Y 坐标
   * @param width 矩形宽度
   * @param height 矩形高度
   */
  private highlightPoint(
    x: number,
    y: number,
    width: number,
    height: number
  ): void {
    const ctx = this.canvas.getContext('2d');
    if (!ctx) return;

    this.init(); // 先重绘所有点
    ctx.strokeStyle = 'yellow';
    ctx.lineWidth = 4;
    ctx.strokeRect(x, y, width, height);
  }

  /**
   * 触发选中点的回调
   */
  private triggerSelection() {
    if (this.onSelect && this.selectedPoint) {
      this.onSelect(this.selectedPoint);
    }
  }

  /**
   * 设置选中点的回调函数
   * @param callback 回调函数
   */
  public setOnSelectCallback(callback) {
    this.onSelect = callback;
  }

  /**
   * 获取选中的点
   */
  public getSelectedPoint() {
    return this.selectedPoint;
  }
}

export default DrawPoint;
